<!-- 首页 -->
<template>
  <div class="complaint-container">
    <!-- 左侧信息卡片 -->
    <div class="card">
      <div class="card-item">
        <text class="card-title">累计有效投诉</text>
        <text class="card-number">{{ totalComplaints }}</text>
      </div>
      <!-- 垂直分割线 -->
      <van-divider vertical :hairline="false" class="divider" />
      <div class="card-item">
        <text class="card-title">24小时有效投诉</text>
        <text class="card-number">{{ dailyComplaints }}</text>
      </div>
    </div>

    <!-- 右侧“我要投诉”按钮 -->
    <!-- <van-button class="complaint-btn" type="primary" round
      ><span>我要投诉</span></van-button
    > -->
    <van-image
      width="143px"
      height="91px"
      fit="contain"
      src="/index_pic01.png"
      class="complaint-btn"
      @click="toComplaints"
    />
  </div>
  <div class="tabs-content">
    <van-tabs v-model:active="activeTab" class="custom-tabs" sticky offset-top="60">
      <van-tab :title="item.tname" v-for="item in titleData" :key="item.tid">
        <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多数据啦～"
      @load="loadData"
    >
      <!-- 单个投诉项 -->
      <div v-for="(complain, index) in pageDate" :key="index" class="complain-item" @click="goToDetail(complain.complaintId)">
        <!-- 头部区域 -->
        <div class="header">
          <img :src="avatar[complain.userId % 4]" class="avatar" />
          <div class="user-info">
            <div class="username">{{ anon[complain.userId % 5] }}</div>
            <div class="date">{{ formatDate(complain.createTime) }} 于黑猫投诉平台发起</div>
          </div>
          <!-- 右上角状态标签 -->
          <div :class="['status-tag', `status-${complain.status}`]">
            <van-icon  class="tag-icon" :name="getStatusIcon(complain.status)"/>
            {{ getStatusText(complain.status) }}
          </div>
        </div>

        <!-- 主体内容 -->
        <div class="content">
          <!-- 标题 -->
          <div class="title-row">
            <span class="hot-label" v-if="titleData[activeTab]?.type === 'hot' && index < 3">热</span>
            <span class="main-title">{{ complain.title }}</span>
          </div>

          <!-- 描述 -->
          <div class="description">{{ complain.description }}</div>

          <!-- 投诉对象和问题 -->
          <div class="details">
            <div class="detail-row">
              <span class="label">投诉对象</span>
              <span class="value">{{ complain.merchantName }}</span>
            </div>
            <div class="detail-row">
              <span class="label">投诉问题</span>
              <van-tag round plain>{{ complain.subject }}</van-tag>
            </div>
          </div>
        </div>
      </div>
    </van-list>
      </van-tab>
      <van-divider />
    </van-tabs>
  </div>
</template>

<script setup>
import { getFindMainComplaintsPage } from "@/api";
import { ref,onMounted,watch,computed } from "vue";
import { useRouter } from "vue-router";

// 模拟后端返回的投诉数据（可根据需求替换为接口请求）
let totalComplaints = ref(29946662);
let dailyComplaints = ref(27407);
const activeTab = ref(0);

const titleData = ref([
  { tid: 1, tname: "最热投诉", type: 'hot' },
  { tid: 2, tname: "最新投诉", type: 'latest' },
  { tid: 3, tname: "已回复", type: 'replied' },
  { tid: 4, tname: "已完成", type: 'resolved' },
]); 



// 匿名列表
const anon = ref([
  "勇敢喵",
  "正义喵",
  "洞察喵",
  "机灵喵",
  "友爱喵"
])
// 头像列表
const avatar = ref([
  "/toux-cat1.png",
  "/toux-cat2.png",
  "/toux-cat3.png",
  "/toux-cat4.png",
])

const statusMap = {
  pending: '待分配',
  processing: '处理中',
  resolved: '已完成',
  replied: '已回复'
};


const statusIcon = {
  pending: '/status-icon4.png',
  processing: '/status-icon2.png',
  resolved: '/status-icon1.png',
  replied: '/status-icon3.png'
}



// 每页大小（和后端一致）
const pageSize = 5;
// ---------- 列表状态 ----------


// 每个 tab 的状态缓存
const tabStates = ref({
  hot: {
    list: [],
    currentPage: 1,
    loading: false,
    finished: false
  },
  latest: {
    list: [],
    currentPage: 1,
    loading: false,
    finished: false
  },
  replied: {
    list: [],
    currentPage: 1,
    loading: false,
    finished: false
  },
  resolved: {
    list: [],
    currentPage: 1,
    loading: false,
    finished: false
  }
});

// 当前激活 Tab 的状态（响应式引用）
const currentTabState = computed(() => {
  const type = titleData.value[activeTab.value]?.type;
  return type ? tabStates.value[type] : null;
});

// 页面显示的数据（响应式）
const pageDate = computed(() => {
  const type = titleData.value[activeTab.value]?.type;
  return type ? tabStates.value[type].list : [];
});

const loading = ref(false);
const finished = ref(false);


// 重置分页状态（切换 tab 时可能需要调用）
// const resetPage = () => {
//   currentPage.value = 1;
//   pageDate.value = [];
//   finished.value = false;
// };

// 通用加载函数
const loadData = async () => {
  const currentType = titleData.value[activeTab.value]?.type;
  if (!currentType) return;

  const state = tabStates.value[currentType];
  if (state.loading || state.finished) return;

  // 更新状态
  state.loading = true;
  loading.value = true; // 👈 同步给 van-list

  try {
    const res = await getFindMainComplaintsPage({
      pageNum: state.currentPage,
      pageSize: pageSize,
      status: currentType
    });

    const newData = res?.data?.pageInfo || res?.pageInfo || [];

    if (newData.length === 0) {
      state.finished = true;
      finished.value = true; // 👈
    } else {
      state.list.push(...newData);
      state.currentPage++;
      // 注意：不要设置 finished，除非没数据
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    finished.value = true; // 防止无限加载
  } finally {
    state.loading = false;
    loading.value = false; // 👈 必须设为 false，否则 van-list 会卡住
  }
};


const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toISOString().split('T')[0]; // 直接取 YYYY-MM-DD
};


// 获取中文状态
const getStatusText = (statusKey) => {
  return statusMap[statusKey] || '未知状态';
};

const getStatusIcon = (statusKey) => {
  return statusIcon[statusKey] || '未知状态';
};

const router = useRouter();

// 跳转详情页方法
const goToDetail = (complaintId) => {
  console.log('跳转详情页', complaintId);
  
  if (complaintId == null) return;
  router.push({
    name: 'complaintDetail',
    params: { cId: complaintId }
  });
};

const toComplaints = () =>{
  router.push({
    name:"complaints"
  })
}

// onMounted(() => {
//   loadData();
// });
// 监听 tab 切换
watch(activeTab, (newIndex) => {
  const type = titleData.value[newIndex]?.type;
  if (!type) return;

  const state = tabStates.value[type];

  // 同步到顶层 loading/finished（供 van-list 使用）
  loading.value = state.loading;
  finished.value = state.finished;

  // 如果当前 Tab 还没加载过数据，则触发加载
  if (state.list.length === 0 && !state.loading && !state.finished) {
    loadData();
  }
}, { immediate: true });
</script>

<style lang="scss" scoped>
.complaint-container {
  height: 90px;
  display: flex;
  overflow-y: auto; /* 允许滚动 */
  align-items: center;
  justify-content: center;
  padding: 10px;
  background-color: #fff; /* 页面背景色，可根据需求调整 */
}


/* 左侧卡片容器 */
.card {
  width: 253px;
  height: 81px;
  display: flex;
  text-align: center;
  align-items: center;
  background-color: #fff;
  border-radius: 16px; /* 卡片圆角 */
  padding: 8px 0px 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 可选阴影增强层次感 */
  margin-right: 10px;

  .divider {
    height: 50px;
  }
}

/* 卡片内的“标题+数字”列 */
.card-item {
  display: flex;
  flex-direction: column; /* 列之间的间距 */
}

/* 标题文字样式（橙色） */
.card-title {
  font-size: 14px;
  color: #f4940e; /* 接近设计图的橙色，可根据需求微调色值 */
  margin-bottom: 8px;
  padding-left: 5px;
}

/* 数字文字样式（黑色、加粗） */
.card-number {
  font-size: 18px;
  color: #000;
  font-weight: bold;
}

/* 右侧按钮样式 */
.complaint-btn {
  padding: 5px 5px; /* 按钮大小，可根据需求调整 */
}
.van-divider {
  margin: 0;
}



/* 整体容器 */
.custom-tabs {
  background-color: #fff;
  z-index: 99;
}

/* 每条投诉项 */
.complain-item {
  padding: 16px 16px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

/* 头部区域 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

/* 头像 */
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

/* 用户信息 */
.user-info {
  margin-left: 12px;
  flex: 1;
}

.username {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.date {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

/* 状态标签 */
.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #ffcc00;
  background-color: #fff;
  border-radius: 4px;
  padding: 2px 8px;
}

.tag-icon {
  font-size: 12px;
}

/* 内容区域 */
.content {
  margin-top: 8px;
}

/* 标题行 */
.title-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.hot-label {
  background-color: #e83c3c;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 6px;
}

.main-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

/* 描述 */
.description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
}

/* 详情行 */
.details {
  margin-top: 8px;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.label {
  font-size: 14px;
  color: #999;
  min-width: 70px;
}

.value {
  font-size: 14px;
  color: #333;
  margin-left: 2px;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  border-radius: 4px;
  padding: 2px 8px;
  font-weight: 500;
}

// 待分配 - 灰色
.status-pending {
  color: #999;
}

// 处理中 - 橙色
.status-processing {
  color: #ff9900;
}

// 已完成 - 绿色
.status-resolved {
  color: #07c160;
}

// 已回复 - 蓝色
.status-replied {
  color: #03bcff;
}
</style>
